package com.adulcimer.core.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Simon
 * @create 2025/7/18
 * @Description WebSocket处理程序
  **/

@Slf4j
@Component
public class WebSocketChatHandler extends TextWebSocketHandler {


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("WebSocket 连接关闭：{}，远程地址：{}", session.getId(), session.getRemoteAddress());
        log.info("关闭status{}", status);

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("WebSocket 连接成功：{}，远程地址：{}", session.getId(), session.getRemoteAddress());

    }

    private void sendMessage(WebSocketSession session, Map<String, Object> messageObj) {
        try {
            session.sendMessage(new TextMessage(new ObjectMapper().writeValueAsString(messageObj)));
        } catch (Exception e) {
            log.error("发送消息失败：{}", e.getMessage(), e);
        }
    }


    private void sendErrorMessage(WebSocketSession session, String errorMessage) {
        try {
            Map<String, Object> errorObj = new HashMap<>();
            errorObj.put("type", "error");
            errorObj.put("message", errorMessage);
            session.sendMessage(new TextMessage(new ObjectMapper().writeValueAsString(errorObj)));
        } catch (Exception e) {
            log.error("发送错误消息失败：{}", e.getMessage(), e);
        }
    }

    private void sendCompletionMessage(WebSocketSession session) {
        try {
            Map<String, Object> completeObj = new HashMap<>();
            session.sendMessage(new TextMessage(new ObjectMapper().writeValueAsString(completeObj)));
        } catch (Exception e) {
            log.error("发送完成消息失败：{}", e.getMessage(), e);
        }
    }


    // 解码Unicode编码的字符串
    private String decodeUnicode(String unicode) {
        if (unicode == null || unicode.isEmpty()) {
            return unicode;
        }

        try {
            // 先处理常见的转义字符
            StringBuilder sb = new StringBuilder();
            int i = 0;
            while (i < unicode.length()) {
                if (unicode.charAt(i) == '\\' && i < unicode.length() - 1) {
                    char nextChar = unicode.charAt(i + 1);
                    switch (nextChar) {
                        case 'n':
                            sb.append('\n');
                            i += 2;
                            continue;
                        case 'r':
                            sb.append('\r');
                            i += 2;
                            continue;
                        case 't':
                            sb.append('\t');
                            i += 2;
                            continue;
                        case 'b':
                            sb.append('\b');
                            i += 2;
                            continue;
                        case 'f':
                            sb.append('\f');
                            i += 2;
                            continue;
                        case '"':
                            sb.append('"');
                            i += 2;
                            continue;
                        case '\\':
                            sb.append('\\');
                            i += 2;
                            continue;
                        case 'u':
                            // 处理Unicode转义序列
                            if (i < unicode.length() - 5) {
                                String hex = unicode.substring(i + 2, i + 6);
                                try {
                                    int codePoint = Integer.parseInt(hex, 16);
                                    sb.append((char) codePoint);
                                    i += 6;
                                } catch (NumberFormatException e) {
                                    // 如果不是有效的十六进制，保持原样
                                    sb.append(unicode.charAt(i));
                                    i++;
                                }
                                continue;
                            }
                        default:
                            break;
                    }
                }
                sb.append(unicode.charAt(i));
                i++;
            }
            return sb.toString();
        } catch (Exception e) {
            log.warn("Unicode解码失败，返回原始字符串: {}", e.getMessage());
            return unicode;
        }
    }



}


